package cn.touna.jss.modules.callback.controller;

import cn.touna.risk.api.enums.IntfTypeEnum;
import cn.touna.risk.api.utils.JSONUtil;
import cn.touna.jss.common.cache.HbaseComponent;
import cn.touna.jss.common.entity.CreditQueryRequest;
import cn.touna.jss.common.mq.KafkaComponent;
import cn.touna.jss.common.util.HttpParseUtil;
import cn.touna.jss.modules.callback.entity.MoxieCallbackEntity;
import cn.touna.jss.modules.callback.enums.MoxieTaskEnum;
import cn.touna.jss.modules.callback.service.ExtCallBackService;
import cn.touna.jss.modules.credit.service.AuthHistoryService;
import cn.touna.jss.modules.third.moxie.MoXieService;
import cn.touna.jss.modules.third.moxie.entity.MoXieEntity;
import cn.touna.risk.api.domain.Response;
import cn.touna.risk.api.exception.ServiceException;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * 魔蝎回调入库
 * Created by wuwc on 2017/12/15.
 */
@RestController
public class MoxieCallbackController {
    private static final Logger logger = LogManager.getLogger(MoxieCallbackController.class);

    @Autowired
    private ExtCallBackService extCallBackService;

    @Autowired
    private MoXieService moXieService;

    @Autowired
    private HbaseComponent hbaseComponent;

    @Autowired
    private KafkaComponent kafkaComponent;

    @Autowired
    private AuthHistoryService authHistoryService;

    @RequestMapping(value = "/moxie/reportNotify", method = {RequestMethod.POST})
    public void reportNotify(@RequestBody String body, HttpServletRequest request, HttpServletResponse response) {
        logger.info("REQ 【魔蝎报告回调请求】,params:{}", body);
        Map<String, String> headParams = new HashMap<>();
        try {
            headParams = HttpParseUtil.getHeadersInfo(request);
            if (StringUtils.isNotBlank(body)) {
                //通知魔蝎收到回调
                response.setStatus(201);
                //解析回调参数，判断是否调用魔蝎接口
                /*Boolean resultFlag = JSONUtil.getBoolean(body, "result", false);
                if (resultFlag != null && resultFlag) {
                    fillQueryRequest(body, headParams);
                }*/
                fillQueryRequest(body, headParams);
            }
        } catch (Exception e) {
            logger.error("RER【魔蝎报告回调发生异常】,params:{},msg:{}", body, e.getMessage());
            response.setStatus(500);
        } finally {
            this.saveCallbackHistory(body, headParams);
        }
    }

    @RequestMapping(value = "/moxie/billNotify", method = {RequestMethod.POST})
    public void billNotify(@RequestBody String body, HttpServletRequest request, HttpServletResponse response) {
        logger.info("REQ 【魔蝎账单回调请求】,params:{}", body);
        Map<String, String> headParams = new HashMap<>();
        try {
            headParams = HttpParseUtil.getHeadersInfo(request);
            if (StringUtils.isNotBlank(body)) {
                //通知魔蝎收到回调
                response.setStatus(201);
                //解析回调参数，判断是否调用魔蝎接口
                fillQueryRequest(body, headParams);
            }
        } catch (Exception e) {
            logger.error("RER【魔蝎账单回调发生异常】,params:{},msg:{}", body, e.getMessage());
            response.setStatus(500);
        } finally {
            this.saveCallbackHistory(body, headParams);
        }
    }


    /**
     * security社保 fund公积金 email邮箱 zhengxin人行征信
     *
     */
    private void fillQueryRequest(String body, Map<String, String> headParams) throws Exception {
        CreditQueryRequest queryRequest = new CreditQueryRequest();
        Response response = new Response();
        queryRequest.setCrNo(JSONUtil.getString(body, "task_id", null));
        queryRequest.setMobile(JSONUtil.getString(body, "user_id", null));
        String moxieType = headParams.get("x-moxie-type");
        String moxieEvent = headParams.get("x-moxie-event");

        if (StringUtils.isAnyBlank(moxieType, moxieEvent)) {
            throw new ServiceException("非法的任务类型");
        }
        String taskType = moxieType.concat("_").concat(moxieEvent);
        /**社保报告**/
        if (MoxieTaskEnum.MOXIE_SECURITY_REPORT.equals(taskType)) {
            queryRequest.setParams(JSONUtil.getJSONObject(body, "task_id", "user_id"));
            queryRequest.setMethod(IntfTypeEnum.MOXIE_SECURITY_REPORT.getCode());
            MoXieEntity moXieEntity = new MoXieEntity();
            moXieEntity.setTask_id(JSONUtil.getString(body, "task_id", null));
            response = moXieService.securityReport(moXieEntity);
        }
        /**社保账单**/
        if (MoxieTaskEnum.MOXIE_SECURITY_BILL.equals(taskType)) {
            queryRequest.setParams(JSONUtil.getJSONObject(body, "task_id", "user_id"));
            queryRequest.setMethod(IntfTypeEnum.MOXIE_SECURITY_BILL.getCode());
            MoXieEntity moXieEntity = new MoXieEntity();
            moXieEntity.setTask_id(JSONUtil.getString(body, "task_id", null));
            response = moXieService.securityBill(moXieEntity);
        }
        /**公积金报告**/
        if (MoxieTaskEnum.MOXIE_FUND_REPORT.equals(taskType)) {
            queryRequest.setParams(JSONUtil.getJSONObject(body, "task_id", "user_id"));
            queryRequest.setMethod(IntfTypeEnum.MOXIE_FUND_REPORT.getCode());
            MoXieEntity moXieEntity = new MoXieEntity();
            moXieEntity.setTask_id(JSONUtil.getString(body, "task_id", null));
            response = moXieService.fundReport(moXieEntity);
        }
        /**公积金账单**/
        if (MoxieTaskEnum.MOXIE_FUND_BILL.equals(taskType)) {
            queryRequest.setParams(JSONUtil.getJSONObject(body, "task_id", "user_id"));
            queryRequest.setMethod(IntfTypeEnum.MOXIE_FUND_BILL.getCode());
            MoXieEntity moXieEntity = new MoXieEntity();
            moXieEntity.setTask_id(JSONUtil.getString(body, "task_id", null));
            response = moXieService.fundBill(moXieEntity);
        }

        /**邮箱报告**/
        if (MoxieTaskEnum.MOXIE_EMAIL_REPORT.equals(taskType)) {
            queryRequest.setParams(JSONUtil.getJSONObject(body, "task_id", "email_id", "user_id"));
            queryRequest.setMethod(IntfTypeEnum.MOXIE_MAIL_REPORT.getCode());
            MoXieEntity moXieEntity = new MoXieEntity();
            moXieEntity.setTask_id(JSONUtil.getString(body, "task_id", null));
            moXieEntity.setEmail_id(JSONUtil.getString(body, "email_id", null));
            response = moXieService.mailReport(moXieEntity);
        }
        /**邮箱账单**/
        if (MoxieTaskEnum.MOXIE_EMAIL_BILL.equals(taskType)) {
            queryRequest.setParams(JSONUtil.getJSONObject(body, "task_id", "user_id"));
            queryRequest.setMethod(IntfTypeEnum.MOXIE_MAIL_BILL.getCode());
            MoXieEntity moXieEntity = new MoXieEntity();
            moXieEntity.setTask_id(JSONUtil.getString(body, "task_id", null));
            response = moXieService.mailBill(moXieEntity);
        }
        /**人行征信暂时不使用**/
        if (MoxieTaskEnum.MOXIE_ZHENGXIN_REPORT.equals(taskType)) {
            queryRequest.setParams(JSONUtil.getJSONObject(body, "task_id", "user_id"));
            queryRequest.setMethod(IntfTypeEnum.MOXIE_ZHENGXIN_REPORT.getCode());
            MoXieEntity moXieEntity = new MoXieEntity();
            moXieEntity.setTask_id(JSONUtil.getString(body, "task_id", null));
        }

        if (MoxieTaskEnum.MOXIE_ZHENGXIN_BILL.equals(taskType)) {
            queryRequest.setParams(JSONUtil.getJSONObject(body, "task_id", "user_id"));
            queryRequest.setMethod(IntfTypeEnum.MOXIE_ZHENGXIN_BILL.getCode());
            MoXieEntity moXieEntity = new MoXieEntity();
            moXieEntity.setTask_id(JSONUtil.getString(body, "task_id", null));
        }
        //结果推送给变量系统
        kafkaComponent.sendSyncCallData(queryRequest, response);

        //结果存储到hbase
        hbaseComponent.saveCacheData(queryRequest, response);

        //保存认证记录
        authHistoryService.saveAuthHistory(queryRequest, response);

    }

    private void saveCallbackHistory(String body, Map<String, String> headParams) {
        try {
            MoxieCallbackEntity moxieCallbackEntity = new MoxieCallbackEntity();
            moxieCallbackEntity.setBizType(headParams.get("biz_type"));
            moxieCallbackEntity.setUserId(JSONUtil.getString(body, "user_id", null));
            moxieCallbackEntity.setMxType(headParams.get("x-moxie-type"));
            moxieCallbackEntity.setMxEvent(headParams.get("x-moxie-event"));
            moxieCallbackEntity.setRequestParams(body);
            moxieCallbackEntity.setResult(JSONUtil.getBoolean(body, "result", false));
            moxieCallbackEntity.setTaskId(JSONUtil.getString(body, "task_id", null));
            extCallBackService.saveMoxieCallbackHistory(moxieCallbackEntity);
            logger.info("【保存魔蝎回调历史成功】,data:{}", moxieCallbackEntity);
        } catch (Exception e) {
            logger.error("RER【保存魔蝎回调历史】异常,requestInfo：{}", body, e.getMessage());
        }
    }

}
